package com.component;

import com.Listener.ActionDoneListener;
import com.util.BaseDao;
import com.util.GetImage;
import com.util.SelectProduct;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class BrowseProductManageComponent extends Box {
    final int WIDTH=1000;
    final int HEIGHT=600;

    JFrame jf = null;
    private JTable table;
    private int Index;
    private JTableHeader jth;
    private JScrollPane scrollPane;
    private Object[][] info;

    public BrowseProductManageComponent(JFrame jf) {
        //垂直布局
        super(BoxLayout.Y_AXIS);
        //组装视图
        this.jf = jf;
        this.Index = 1; //初始化从第一页开始查看

        scrollPane = new JScrollPane();
        JPanel btnPanel = new JPanel();
        Color color = new Color(203, 220, 217);
        btnPanel.setBackground(color); //设置背景颜色
        btnPanel.setMaximumSize(new Dimension(WIDTH, 80)); //设置最大宽高
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); // 默认的panel是从左侧开始的流式布局，此处设置为从右侧开始布局的流式布局

        JButton prevBtn = new JButton("上一页");
        JButton nextBtn = new JButton("下一页");
        JButton firstBtn = new JButton("首页");
        JButton lastBtn = new JButton("尾页");

        //上一页的监听
        prevBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(--Index==0){
                    JOptionPane.showMessageDialog(jf,"当前页面已是首页！");
                }
                else{
                    requestBrowseProductData(Index);
                }
            }
        });

        //下一页的监听
        nextBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(++Index==new SelectProduct().getProductNumber()/10+2){
                    JOptionPane.showMessageDialog(jf,"当前页面已是尾页！");
                }
                else{
                    requestBrowseProductData(Index);
                }
            }
        });

        //首页的监听
        firstBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Index = 1;
                requestBrowseProductData(Index);
            }
        });

        //尾页的监听
        lastBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Index = new SelectProduct().getProductNumber()/10+1;
                requestBrowseProductData(Index);
            }
        });

        //组装表格
        btnPanel.add(prevBtn);
        btnPanel.add(nextBtn);
        btnPanel.add(firstBtn);
        btnPanel.add(lastBtn);
        this.add(btnPanel); // 将按钮添加进去

        //向数据库请求数据
        requestBrowseProductData(Index);
        //设置只能选中一行
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    // 获取选中的行索引
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow != -1) {
                        // 获取选中行的数据
                        Object[] rowData = info[selectedRow];
                        // 显示农产品图片
                        showImage((String)rowData[4],(String)rowData[2]);
                    }
                }
            }
        });

    }
    // 显示图片的方法
    private void showImage(String imagePath,String ProductName) {
        try {
            // 从文件路径创建图像
            ImageIcon ProductImage = new ImageIcon(new GetImage().getImage(imagePath));
            // 调整图像大小以适应 JLabel
            Image scaledImage = ProductImage.getImage().getScaledInstance(200, 200, Image.SCALE_SMOOTH);
            // 设置调整大小后的图像到 JLabel
            JLabel imageLabel = new JLabel();
            //imageLabel.setIcon(ProductImage);
            imageLabel.setIcon(new ImageIcon(scaledImage));
            JOptionPane.showMessageDialog(this,imageLabel,ProductName,JOptionPane.PLAIN_MESSAGE);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常，例如文件不存在等情况
            JOptionPane.showMessageDialog(this, "无法加载图片: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    //请求数据
    public void requestBrowseProductData(int PageIndex) {
        Connection conn = new BaseDao().getConn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String sql = "exec PartPage @PageSize = ?,@PageIndex = ?";
            ps = conn.prepareStatement(sql); //编译sql语句
            ps.setInt(1, 10);
            ps.setInt(2, PageIndex);

            rs = ps.executeQuery();
            int count = 0;
            while (rs.next()) {
                count++;
            }
            rs = ps.executeQuery();
            // 将查询获得的记录数据，转换成适合生成JTable的数据形式
            String[] ts = {"农产品编号", "农产品类型", "农产品名称", "农产品价格", "图片路径", "描述信息"};
            info = new Object[count][6];
            count = 0;
            while (rs.next()) {
                info[count][0] = String.valueOf(rs.getInt("ProductID"));
                info[count][1] = "" + rs.getInt("ProductCategoryID");
                info[count][2] = rs.getString("ProductName");
                info[count][3] = rs.getString("Price");
                info[count][4] = rs.getString("ImagePath");
                info[count][5] = rs.getString("description");
                count++;
            }
            this.table = new JTable(info, ts) {
                @Override //设置不可编辑
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            //显示表头
            this.jth = this.table.getTableHeader();
            //设置滚动条
            this.scrollPane.getViewport().add(table);
            this.add(scrollPane);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接数据库失败！");
        } finally {
            //关闭coon
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭ps
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            //关闭rs
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
